<script setup>
import Header from "@/components/Header.vue";
import MyList from "@/components/MyList.vue";
import Footer from "@/components/Footer.vue";
import {defineComponent, onBeforeUnmount, onMounted, provide, reactive} from "vue";
import emitter from "@/../eventBus";

defineComponent({
  Header, MyList, Footer
})
const tableData = reactive({'data': []});
const storageData = JSON.parse(localStorage.getItem('tableData'));
if (storageData) tableData.data = storageData

provide('tableData', tableData)

const handleReceive = (dataItem) => {
  tableData.data.push(dataItem)
}

const handleCheckTodo = (value) => {
  tableData.data.forEach(item => {
    item.done = value
  })
}

const handleClearAll = () => {
  tableData.data = tableData.data.filter(item => {
    return item.done === false
  })
}

onMounted(() => {
  emitter.on('handleEditData', data => {
    tableData.data.some(item => {
      if (item.id === data.itemId) {
        item.title = data.itemValue
        return true
      }
    })
  })
  emitter.on('handleCheckedTableData', itemId => {
    tableData.data.forEach(item => {
      if (item.id === itemId) item.done = !item.done
    })
  })
  emitter.on('handleDeleteData', itemId => {
    tableData.data = tableData.data.filter(item => {
      return item.id !== itemId
    })
  })
})

onBeforeUnmount(() => {
  emitter.off('handleEditData')
  emitter.off('handleCheckedTableData')
  emitter.off('handleDeleteData')
})

</script>

<template>
  <Header @handleReceive="handleReceive"></Header>
  <MyList :table-data="tableData.data"></MyList>
  <Footer :todos="tableData.data"
          @handleCheckTodo="handleCheckTodo"
          @handleClearAll="handleClearAll"
  ></Footer>
</template>

<style>

</style>
